import { assert, AudioClip, AudioSource, resources, _decorator } from "cc";
import { injectable, InjectableObject } from "../inject";

const { ccclass, property } = _decorator;

@injectable("SoundManager")
export default class SoundManager extends InjectableObject {

    private _audioSource?: AudioSource;

    private musicMute = false;
    private effectMute = false;

    private _audioCache: Map<string, AudioClip> = new Map();

    /**管理器初始化*/
    public init(audioSource: AudioSource) {
        this._audioSource = audioSource;
    }

    /**
     * 播放音乐
     * @param {Boolean} loop 是否循环播放
     */
    playMusic(loop: boolean = true) {
        const audioSource = this._audioSource!;
        assert(audioSource, 'AudioManager not inited!');

        audioSource.loop = loop;
        if (!audioSource.playing) {
            audioSource.play();
        }
    }


    /**
     * 播放音效
     * @param {String} name 音效名称
     * @param {Number} volumeScale 播放音量倍数
     */
    playSound(name: string, volumeScale: number = 1) {
        if (this.effectMute) {
            return -1;
        }

        const audioSource = this._audioSource!;
        assert(audioSource, 'AudioManager not inited!');

        this.loadAudio(name, (audioClip: AudioClip) => {

            if (audioClip) {
                // 注意：第二个参数 “volumeScale” 是指播放音量的倍数，最终播放的音量为 “audioSource.volume * volumeScale”
                audioSource.playOneShot(audioClip, volumeScale);
            }
        });



    }

    public loadAudio(path: string, ...args: Function[]): boolean {
        const complete = (args[1] || args[0]) as (result: any) => any;

        let prefab = this._audioCache.get(path)
        if (prefab) {
            complete && complete(prefab);
            return true;
        }

        resources.load(path, AudioClip, function (err, clip) {

            // this._audioCache[path] = clip;
            // this._audioCache.set(path, clip);
            complete && complete(clip);
        })

        return false;
    }
}

